# -*- coding: utf-8 -*-

from spider.pagerank import get_pagerank
from flask.ext.restful import Resource, abort
from PalmWebsite.api import parser
from PalmWebsite.model import Site, SiteSE
import utils
from datetime import datetime, date
from PalmWebsite.extensions import db


class PageRank(Resource):

    def get(self, id=None):
        args = parser.parse_args()
        domain = args.get("domain")

        if id:
            site = Site.query.get(id)
        elif domain:
            site = Site.query.filter_by(domain=utils.get_host(domain)).first()

        if id is None and not domain:
            abort(400, success=False, err_code=10000)

        if not site:
            if id:
                abort(404, err_code=30000, success=False)
            data = get_pagerank(domain)

            return {
                    "success": True,
                    "data": {
                        "domain": domain,
                        "pagerank": data
                    }
                }

        if args.get("refresh"):
            data = get_pagerank(site.domain)
            site.pagerank = data
            site.last_update_date = date.today()
            db.session.commit()

        return {
                "success": True,
                "data": {
                    "domain": site.domain,
                    "pagerank": site.pagerank,
                    "id": site.id,
                    "last_update_date": utils.date2string(site.last_update_date)
                }
            }
